<template>
  <p-modal
    title="设置显示字段"
    :visible="visible"
    :confirm-loading="confirmLoading"
    :mask-closable="false"
    :top="600"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <p-table
      :columns="columns"
      row-key="dataIndex"
      :data-source="dataSource"
      :scroll="{ y: 300 }"
      :row-selection="{
        selectedRowKeys: selectedRowKeys,
        onChange: onSelectChange,
        getCheckboxProps: getCheckboxProps,
      }"
      bordered
      :pagination="false"
    />
  </p-modal>
</template>
<script>
export default {
  props: {
    visible: {
      type: [Boolean],
      default: false,
    },
    fileds: {
      type: Array,
      default: () => [
        {
          dataIndex: 'customerCode',
          title: '客户简称',
          required: true,
        },
        {
          title: '客户项目',
          dataIndex: 'item',
          required: false,
        },
      ],
    },
  },
  data() {
    return {
      selectedRowKeys: [],
      columns: [
        {
          align: 'center',
          title: '序号',
          width: 60,
          customRender(t, r, index) {
            return parseInt(index) + 1;
          },
        },
        {
          align: 'center',
          title: '字段名称',
          dataIndex: 'title',
        },
      ],
    };
  },
  computed: {
    dataSource() {
      return this.fileds
        .filter((item) => item.dataIndex && !item.isHide)
        .filter((item) => item.dataIndex !== 'selection')
        .map((item) => {
          return {
            dataIndex: item.dataIndex,
            title: item.title,
            required: item.required,
          };
        });
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.selectedRowKeys = this.dataSource.map((item) => item.dataIndex);
        }
      },
    },
  },
  methods: {
    handleCancel() {
      this.$emit('update:visible', false);
    },
    handleOk() {
      if (this.selectedRowKeys.length) {
        this.handleCancel();
        this.$emit('confirm', this.selectedRowKeys);
      } else {
        this.$message.error('请选择显示字段！');
      }
    },
    onSelectChange(selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys;
    },
    getCheckboxProps(record) {
      // console.log(record);
      return {
        props: {
          disabled: record.required,
        },
      };
    },
  },
};
</script>

<style lang="less" scoped>
/deep/ .poros-table-tbody > tr > td {
  padding: 2px;
}
/deep/ .poros-table-thead > tr > th {
  padding: 0;
}
</style>
